package com.miao.im.server.session;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.miao.im.model.AuthResponseModel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;

import java.net.InetSocketAddress;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/2/25 15:36
 * @Description:
 */
@Data
public class SessionContext {
    /**web登录时候的sessionId*/
    private String sessionId;
    /**用户信息*/
    private AuthResponseModel.AuthResponse userInfo;
    /**客户端host*/
    private RemoteNode remoteNode;
    /**已加入的群组*/
    private Set<String> groupIds;
    /**连接映射通道*/
    private Channel channel;
    private ChannelHandlerContext ctx;
    /**读空闲次数*/
    private AtomicInteger readIdleTimes = new AtomicInteger(0);


    public SessionContext(ChannelHandlerContext ctx) {
        this.channel = ctx.channel();
        this.ctx = ctx;
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        this.remoteNode = new RemoteNode(remoteAddress.getHostString(), remoteAddress.getPort());
        this.groupIds = new ConcurrentHashSet<>();
    }

    /**
     * @Description: 是否通过了权限认证
     * @Author: miaoguoxin
     * @Date: 2021/5/11
     */
    public boolean isAuth() {
        return userInfo != null;
    }

    public int incAndGetReadIdleTimes() {
        return readIdleTimes.incrementAndGet();
    }

    public void resetReadIdleTimes() {
        readIdleTimes.set(0);
    }

    public void addGroup(String groupId) {
        this.groupIds.add(groupId);
    }

    public void removeGroup(String groupId) {
        this.groupIds.remove(groupId);
    }
}
